<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>

<form id="role-add-form" method="post" style="padding: 10px;">  
    <div>   
        <label for="name">名称:</label><span>&nbsp;&nbsp;&nbsp;&nbsp;</span>   
        <input class="easyui-validatebox" type="text" name="name" 
         data-options="required:true,missingMessage:'角色名称不能为空'" onblur="role.checkName(this.value)" />
        <span id="name-tip"></span>
    </div>
</form>  

<script type="text/javascript">
	role.add=function(){
		$('#role-add-form').form('submit', {
			url: '/role/add',
			onSubmit: function(){
				var isValid = $(this).form('validate');
				var name = $('#role-add-form input[name="name"]').val();
				var flag = role.checkName(name);
				return isValid && flag;	// 返回false终止表单提交
			},
			success: function(msg){
				//把字符串转化成 json对象
				var msg = JSON.parse(msg);
				if(msg.code == 200){
					//添加成功后，更新表格
					$('#role-list-dg').datagrid('reload');
					$.messager.alert('提示','添加成功！','info');
				}
			}
		});
	}
	
	role.checkName=function(name){
		var name = $.trim(name);
		if(name == ''){
			return;
		}
		//名称被占用
		var flag= false;
		
		//改成同步
		$.ajax({
		   type: "get",
		   async:false,
		   url: "/role/name/check",
		   data: "name="+name,
		   success: function(msg){
		     if(msg.code == 200 && !msg.data){
		    	 $('#name-tip').html("<font color='green'>该名称可以使用</font>");
		    	 flag = true;
		     }else if(msg.code == 200 && msg.data){
		    	 $('#name-tip').html("<font color='red'>该名称已被使用</font>");
		     }
		   }
		});
		
		return flag;
	}
</script>